package org.mihalovic.PES.Application;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import javax.swing.JOptionPane;



/**
 * Application configuration manager. Reads values from configuration file named app.config and placed in the same
 * folder as this program.
 * 
 * @author Martin Mihalovic (with help of Google)
 * @see http://programmersjournal.blogspot.com/2008/09/java-configuration-file-vs-net.html
 */
public class AppConfiguration {

    private static String configFile = new File("app.config").getAbsolutePath();



    /** Reads a value with given key and returns in String form. */
    public static String ReadValue(String key) throws Exception, ConfigurationException {

        FileInputStream stream = null;
        try {
            Properties vProp = new Properties();
            stream = new FileInputStream(configFile);
            vProp.loadFromXML(stream);
            String value = vProp.getProperty(key);
            if(value==null || value.isEmpty())
                throw new ConfigurationException(key);
            return value;
        } catch (ConfigurationException ce) {
            JOptionPane.showMessageDialog(null, "Unable to read configuration key '"+ce.getKey()+"' or its value is empty",
                                          "Fatal error", JOptionPane.ERROR_MESSAGE);
            throw ce;
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Unable to read configuration from file " + configFile, "Fatal error", JOptionPane.ERROR_MESSAGE);
            throw ex;
        }
    }
}


class ConfigurationException extends Exception {
    
    private String key;
    
    public String getKey() { return key; }

    public ConfigurationException(String key) {
        this.key = key;
    }
}
